<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ include file="/WEB-INF/decorators/taglibs.jsp"%>
<div class="w1a">
<div class="w2">資料維護 » 委員名單  </div>
	<br/> 
	<table>
		<tr height="20px">
			<td><font id="hid1" color="red">更新成功</font></td>
			<td><font id="hid2" color="red">更新成功</font></td>
			<td><font id="hid" color="red">更新成功</font></td>
		</tr>
		<tr>
			<td>
				<table id="dg1" class="easyui-datagrid" style="height:600px;width:300px;"  url="${appPath}/committeeTeam/list.json" 
					striped="true" title="群組設定"
					data-options="
					singleSelect: true,
			        toolbar: '#tb1',
			        method: 'post',
			        checkOnSelect:false,
			        loadFilter: loadFilter,
			        onBeforeLoad: onBeforeLoad1,
			        onClickCell: onClickCell1,
			        onBeforeEdit: onBeforeEdit1,
			        onAfterEdit: onAfterEdit1,
			        onCancelEdit: onCancelEdit1,
			        onLoadSuccess: onLoadSuccess1,
					">
					<thead><tr>
						<th data-options="field:'enable',checkbox:true"></th>
				        <th field="date" width="120" editor="datebox">日期</th>
				        <!-- <th field="enable" width="50" editor="checkbox">啟用</th> -->
				        <th field="action" width="120" formatter="action1">作業</th>  
					</tr></thead>   
				</table> 
			</td>
			<td>
				<table id="dg2" class="easyui-datagrid" style="height:600px;width:300px;"  url="${appPath}/ctmap/list.json"  
					striped="true" title="群組委員"
					data-options="
					singleSelect: true,
			        toolbar: '#tb2',
			        method: 'post',
			        checkOnSelect:false,
			        loadFilter: loadFilter,
			        onBeforeLoad: onBeforeLoad2,
			        onClickCell: onClickCell2,
			        onBeforeEdit: onBeforeEdit2,
			        onAfterEdit: onAfterEdit2,
			        onLoadSuccess: onLoadSuccess2,
					">
					<thead><tr>
				        <th field="committee.name" width="200" >名稱</th>
				        <th field="sort" width="50" editor="numberbox">排序</th>
					</tr></thead>   
				</table> 
			</td>
			<td>
				<table id="dg" class="easyui-datagrid" style="height:600px;width:320px;" url="${appPath}/committee/list.json"  
					striped="true" title="委員名單"
					data-options="
					 singleSelect:false,
			        toolbar: '#tb',
			        method: 'post',
			        checkOnSelect:false,
			        onBeforeLoad: onBeforeLoad,
			        onClickCell: onClickCell,
			        onBeforeEdit: onBeforeEdit,
			        onAfterEdit: onAfterEdit,
			        onCancelEdit: onCancelEdit,
			        onLoadSuccess: onLoadSuccess,
					">
					<thead><tr>
						<th data-options="field:'committee',checkbox:true"></th>
				        <th field="name" width="180" editor="text">名稱</th>
				        <th field="action" width="120" formatter="action">作業</th>  
					</tr></thead>   
				</table> 
			</td>
		</tr>
	</table>
	
   <div id="tb1" style="height: auto">   
		<a href="javascript:void(0)" class="easyui-linkbutton" onclick="endEditing1();checking1();">存檔</a>
	</div>
	<div id="tb2" style="height: auto">   
		<a href="javascript:void(0)" class="easyui-linkbutton" onclick="endEditing2()">存檔</a>
	</div>
	<div id="tb" style="height: auto">   
		<a href="javascript:void(0)" class="easyui-linkbutton" onclick="endEditing()">存檔</a>
		<a href="javascript:void(0)" class="easyui-linkbutton" onclick="checking()">建立群組</a>
	</div>
</div>
<script>
$().ready(function() { 
	$( "font[id*='hid']" ).hide();
});
function runEffect(id) {
    $( "#hid"+id ).show( "highlight", {}, 500, function(){
    	setTimeout(function() {
   		   $( "#hid"+id+":visible" ).fadeOut();
   		 }, 1500 );
    } );
};
function loadFilter(data) {

	var value = {
		total : data.total,
		rows : []
	};
	for (var i = 0; i < data.rows.length; i++) {
		var o = {};
		_loadArray(data.rows[i], o, "");
		value.rows.push(o);
	}
	return value;
}
function _loadArray(data, o, pre) {
	if (pre)
		pre = pre + ".";
	for ( var att in data) {
		var row = data[att];
		if (typeof (row) == "object") {
			_loadArray(row, o, pre + att);
		} else {
			if (/\d{4}-\d{2}-\d{2}/.test(row)) {
				o[pre + att] = row.replace(/\-/g, "/");
			} else {
				o[pre + att] = row;
			}
		}

	}
}

//cell edit
$.extend($.fn.datagrid.methods, {
	editCell : function(jq, param) {
		return jq.each(function() {
			var fields = $(this).datagrid('getColumnFields', true).concat(
					$(this).datagrid('getColumnFields'));
			for (var i = 0; i < fields.length; i++) {
				var col = $(this).datagrid('getColumnOption', fields[i]);
				col.editor1 = col.editor;
				if (fields[i] != param.field) {
					col.editor = null;
				}
			}
			$(this).datagrid('beginEdit', param.index);
			for (var i = 0; i < fields.length; i++) {
				var col = $(this).datagrid('getColumnOption', fields[i]);
				col.editor = col.editor1;
			}
		});
	}
});

//=========================================================================================
//群組設定	
function checking1(){
	var checkedItems = $('#dg1').datagrid('getChecked');
    $.each(checkedItems, function(index, item){
    	$.get("${appPath}/committeeTeam/"+item.tCode+"/update.json", 
    			function(data) {
    				if (eval(data)) {
    					alert("更新成功!");
    				}else{
    					alert("更新失敗!");
    				}
    		});
    	
    });      
}
var editIndex1 = undefined; // 目前編輯的row index
function endEditing1() {
	if (editIndex1 == undefined) {
		return true;
	}
	if ($("#dg1").datagrid("validateRow", editIndex1)) {
		$("#dg1").datagrid("endEdit", editIndex1);
		$("#dg1").datagrid("cancelEdit", editIndex1);
		editIndex1 = undefined;
		return true;
	} else {
		/*取消編輯狀態*/
		var ed = $("#dg1").datagrid("getEditor", {index:editIndex1,field:"date"});
		if($(ed.target).text('getValue')==""){
			$('#dg1').datagrid('endEdit', editIndex1);
			$('#dg1').datagrid('cancelEdit', editIndex1);
			return true;
		}
		return false;
	}
}
function onBeforeLoad1(param){
	/* $.each($('#searchForm').serializeArray(), function(i, v) { param[v.name] = v.value;}); */
}
function onClickCell1(index, field, value){
	if(field!='action'){
		if (endEditing1()) {
			$("#dg1").datagrid("selectRow", index).datagrid('beginEdit',index);
			editIndex1 = index;
		} else {
			$("#dg1").datagrid("selectRow", editIndex1);
		}
	}else{
		var o = $("#dg1").datagrid("getData").rows[index];
		$("#dg2").datagrid("load", {tCode:o.tCode});
	}
}
function onBeforeEdit1(index, row, changes) {
	row.editing = true;
    $("#dg1").datagrid("refreshRow", index);
}
function onAfterEdit1(index, row, changes) {
		row.editing = false;
	    $("#dg1").datagrid("refreshRow", index);
	if (Object.keys(changes).length > 0) { 
	    update1(index);
	}
}
function onCancelEdit1(index, row, changes) {
	row.editing = false;
    $("#dg1").datagrid("refreshRow", index);
}
function appendRow1(){
	/* 初始提供一空白行供新增 */
	$("#dg1").datagrid("appendRow", {
	});
}
function onLoadSuccess1(data) {
	appendRow1();
	if (editIndex1 != undefined) { /* 如果為繼續，於reload後將該行設為editable */
		$("#dg1").datagrid('selectRow', editIndex).datagrid('beginEdit',
				editIndex1);
	}
	if(data){
        $.each(data.rows, function(index, item){
            if(item.enable){
                $('#dg1').datagrid('checkRow', index);
            }
        });
    }
	/* 一開始即帶出被選取的群組委員 */
	var selectedItems = $('#dg1').datagrid('getSelections');
	if(selectedItems[0].tCode== undefined||selectedItems[0].tCode==""){
    	return;
    }
	$("#dg2").datagrid("load", {tCode:selectedItems[0].tCode});

	
}
function update1(index) {
	var o = $("#dg1").datagrid("getData").rows[index];  
	if(o.date==""){
		return;
	}
	$.post("${appPath}/committeeTeam/update.json", o,
		function(data) {
			if (!data) {
				alert("更新失敗!");
			} else{
				$("#dg1").datagrid("refreshRow", index);
				if(o.tCode == undefined){
					$('#dg1').datagrid('updateRow', {
						index : index,
						row: {
							tCode: data.tCode
						}
					});
					appendRow1();
				}
			}
	});
}
function cancel1(target){
    $("#dg1").datagrid("cancelEdit", getRowIndex(target));
    editIndex1 = undefined;
}
function remove1(target){
    $.messager.confirm("Confirm","確定刪除?",function(r){
        if (r){
        	var index = getRowIndex(target);
        	var o = $("#dg1").datagrid("getData").rows[index];
            $.post("${appPath}/committeeTeam/delete/"+o.tCode+".json", 
       			function(data) {
       				if (data) {
       					$("#dg1").datagrid("deleteRow", index);
       					if(editIndex1>index){
       						editIndex1 -= 1;
       					}
       				} else {
       					alert("刪除失敗!");
       				}
       				if(editIndex1==index){
       					editIndex1 = undefined;
       				}
       		});
        }
    }); 
}
function action1(val, row, ix) {var str = "";
	var o = $("#dg1").datagrid("getData").rows[ix];
	if(o.tCode!=undefined){
		str = str.concat("[<a href='#do' onclick=\"remove1(this);\" >刪除</a>]");
	}
	if (row.editing){
		str = str.concat("[<a href='#do' onclick=\"cancel1(this);\" >取消</a>]");
	}
	return str; 
}
//群組設定	
//=========================================================================================
//群組委員

var editIndex2 = undefined; // 目前編輯的row index
function endEditing2() {
	if (editIndex2 == undefined) {
		return true;
	}
	if ($("#dg2").datagrid('validateRow', editIndex2)) {
		$('#dg2').datagrid('endEdit', editIndex2);
		$('#dg2').datagrid('cancelEdit', editIndex2);
		editIndex2 = undefined;
		return true;
	} else {
		return false;
	}
}
function onBeforeLoad2(param){
}
function onClickCell2(index, field, value){
	if (endEditing2()) {
		$("#dg2").datagrid("selectRow", index).datagrid('beginEdit',index);
		editIndex2 = index;
	} else {
		$("#dg2").datagrid("selectRow", editIndex2);
	}
}
function onBeforeEdit2(index, row, changes) {
	row.editing = true;
    $("#dg2").datagrid("refreshRow", index);
}
function onAfterEdit2(index, row, changes) {
		row.editing = false;
	    $("#dg2").datagrid("refreshRow", index);
	if (Object.keys(changes).length > 0) { 
	    update2(index);
	}
}
function onLoadSuccess2(data) {
	if (editIndex2 != undefined) { /* 如果為繼續，於reload後將該行設為editable */
		$("#dg2").datagrid('selectRow', editIndex).datagrid('beginEdit',
				editIndex2);
	}
	/* test 將委員勾選 */
	/* $.each(o, function(index1, item1){
		alert(item1.code);
		$.each(data.rows, function(index2, item2){
			alert(item1.code+"   "+item2.committee.code);
			if(item1.code==item2.committee.code){
				$('#dg').datagrid('checkRow', index1);
			}
	
		});
            
    }); */
}
function update2(index) {
	var o = $("#dg2").datagrid("getData").rows[index];  
	$.post("${appPath}/ctmap/update.json", o,
		function(data) {
			if (!eval(data)) {
				alert("更新失敗!");
			} else{
				runEffect("2");
			}
	});
}
function getRowIndex2(target){
    var tr = $(target).closest("tr.datagrid-row");
    return parseInt(tr.attr("datagrid-row-index"));
}
//群組委員
//=========================================================================================
//委員名單
function checking(){
	var selectedItems = $('#dg1').datagrid('getSelections');
	if(selectedItems[0].tCode== undefined||selectedItems[0].tCode==""){
    	return;
    }
	var array = [];
	var checkedItems = $('#dg').datagrid('getChecked');
    $.each(checkedItems, function(index, item){
    	array.push(item.code);
    });  
    var param = {};
    param['name']= array.join();
    $.post("${appPath}/committeeTeam/"+selectedItems[0].tCode+"/updateGroup.json",param,
			function(data) {
				if (!data) {
					alert("更新失敗!");
				} else{
					runEffect("");
					var selectedItems = $('#dg1').datagrid('getSelections');
					if(selectedItems[0].tCode== undefined||selectedItems[0].tCode==""){
				    	return;
				    }
					$("#dg2").datagrid("load", {tCode:selectedItems[0].tCode});
				}
		});
}
var editIndex = undefined; // 目前編輯的row index
function endEditing() {
	if (editIndex == undefined) {
		return true;
	}
	if ($("#dg").datagrid('validateRow', editIndex)) {
		$('#dg').datagrid('endEdit', editIndex);
		$('#dg').datagrid('cancelEdit', editIndex);
		editIndex = undefined;
		return true;
	} else {
		/*取消編輯狀態*/
		var ed = $("#dg").datagrid("getEditor", {index:editIndex,field:"name"});
		if($(ed.target).text('getValue')==""){
			$('#dg').datagrid('endEdit', editIndex);
			$('#dg').datagrid('cancelEdit', editIndex);
			return true;
		}
		return false;
	}
}
function onBeforeLoad(param){
	/* $.each($('#searchForm').serializeArray(), function(i, v) { param[v.name] = v.value;}); */
}
function onClickCell(index, field, value){
	if(field!='action'){
		if (endEditing()) {
			$("#dg").datagrid("selectRow", index).datagrid('beginEdit',index);
			editIndex = index;
		} else {
			$("#dg").datagrid("selectRow", editIndex);
		}
	}
}
function onBeforeEdit(index, row, changes) {
	row.editing = true;
    $("#dg").datagrid("refreshRow", index);
}
function onAfterEdit(index, row, changes) {
		row.editing = false;
	    $("#dg").datagrid("refreshRow", index);
	if (Object.keys(changes).length > 0) { 
	    update(index);
	}
}
function onCancelEdit(index, row, changes) {
	row.editing = false;
    $("#dg").datagrid("refreshRow", index);
}
function appendRow(){
	/* 初始提供一空白行供新增 */
	$("#dg").datagrid("appendRow", {
		name : "",
	});
}
function onLoadSuccess(data) {
	appendRow();
	if (editIndex != undefined) { /* 如果為繼續，於reload後將該行設為editable */
		$("#dg").datagrid('selectRow', editIndex).datagrid('beginEdit',
				editIndex);
	}
}
function update(index) {
	var o = $("#dg").datagrid("getData").rows[index];  
	if(o.name==""){
		return;
	}
	$.post("${appPath}/committee/update.json", o,
		function(data) {
			if (!data) {
				alert("更新失敗!");
			} else{
				$("#dg").datagrid("refreshRow", index);
				if(o.code == undefined){
					$('#dg').datagrid('updateRow', {
						index : index,
						row: {
							code: data.code
						}
					});
					appendRow();
				}
			}
	});
}
function getRowIndex(target){
    var tr = $(target).closest("tr.datagrid-row");
    return parseInt(tr.attr("datagrid-row-index"));
}
function cancel(target){
    $("#dg").datagrid("cancelEdit", getRowIndex(target));
    editIndex = undefined;
}
function remove(target){
    $.messager.confirm("Confirm","確定刪除?",function(r){
        if (r){
        	var index = getRowIndex(target);
        	var o = $("#dg").datagrid("getData").rows[index];
            $.post("${appPath}/committee/delete/"+o.code+".json", 
       			function(data) {
       				if (data) {
       					$("#dg").datagrid("deleteRow", index);
       					if(editIndex>index){
       						editIndex-=1;
       					}
       				} else {
       					alert("刪除失敗!");
       				}
       				if(editIndex==index){
       					editIndex = undefined;
       				}
       		});
        }
    }); 
}
function action(val, row, ix) {var str = "";
	var o = $("#dg").datagrid("getData").rows[ix];
	if(o.code!=undefined){
		str = str.concat("[<a href='#do' onclick=\"remove(this);\" >刪除</a>]");
	}
	if (row.editing){
		str = str.concat("[<a href='#do' onclick=\"cancel(this);\" >取消</a>]");
	}
	return str; 
}
</script>